<?php
/**
 * Created by ptmall
 * User : 河南邦耀网络科技有限公司
 * Date : 2020/9/4
 * Time : 16:26
 */

namespace app\api\controller;


use app\admin\model\goods\Cart as Cm;
use app\admin\model\goods\GoodsSkuDetail;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Cart extends Api
{
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * @Explain :加入购物车
     * @Date : 2020/9/7 16:59
     * @Author : 河南邦耀网络科技有限公司
     */
    public function add(){
        $userInfo=$this->auth->getUser();
        $goodsId = $this->request->request("goodsId",'');
        $skuId = $this->request->request("skuId",'');
        $quantity = $this->request->request("quantity");
        $sku=(new GoodsSkuDetail())->where(['skuId'=>$skuId])->find();
        if(empty($sku)) $this->error('商品信息错误');
        $cart=(new Cm())->where(['uid'=>$userInfo->id,'goodsId'=>$goodsId,'skuId'=>$skuId,'status'=>1])->find();
        if(!empty($cart)){
            $quantity+=$cart['quantity'];
            $r=(new Cm())->save(['quantity'=>$quantity],['uid'=>$userInfo->id,'goodsId'=>$goodsId,'skuId'=>$skuId]);
            $this->success('添加成功');
        }
        try {
            $data=[
                'uid'=>$userInfo->id,
                'goodsId'=>$goodsId,
                'skuId'=>$skuId,
                'quantity'=>$quantity,
                'ctime'=>time(),
            ];
            (new Cm())->insert($data);
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success('添加成功');
    }
    /**
     * @Explain :更新购物车
     * @Date : 2020/9/7 16:59
     * @Author : 河南邦耀网络科技有限公司
     */

    public function update(){
        $userInfo=$this->auth->getUser();
        $goodsId = $this->request->request("goodsId");
        $skuId = $this->request->request("skuId");
        $quantity = $this->request->request("quantity");
        try {
            (new Cm())->save(['quantity'=>$quantity],['uid'=>$userInfo->id,'goodsId'=>$goodsId,'skuId'=>$skuId]);
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success('修改成功');
    }

    /**
     * @Explain :获取购物车
     * @Date : 2020/9/7 17:29
     * @Author : 河南邦耀网络科技有限公司
     */
    public function getList(){
        $cm=new Cm();
        $userInfo=$this->auth->getUser();
        $pn = $this->request->request('pn',1);
        $selfCateId=$this->request->request('selfCateId',0);
        $condition=['uid'=>$userInfo->id,'status'=>1];
        if($selfCateId){
            $condition['selfCateId']=$selfCateId;
        }
        $cart=$cm->where($condition)->page($pn,10)->select();
        if(empty($cart)) $this->success('购物车没有商品');
        $goodsIds=array_column($cart,'goodsId');
        $goodsModel=new \app\admin\model\goods\Goods();
        $condition=['goodsid'=>['in',$goodsIds]];
        $data=$goodsModel->field(['goodsid','title','image','sales','price','selfCateId','status','discount'])->where($condition)->select();
        foreach ($cart as $row){
            $sku[]=(new GoodsSkuDetail())->field(['goodsId,skuId,title,price,image'])->where(['goodsId'=>$row['goodsId'],'skuId'=>$row['skuId']])->find();
        }
        $data=collection($data)->toArray();
        $sku=collection($sku)->toArray();
        $sku=array_column($sku,null,'skuId');
        $result=[];
        foreach ($sku as $key=>&$item){

            foreach ($cart as $row) {
                if ($item['skuId'] == $row['skuId']) {
                    $item['quantity'] = $row['quantity'];
                }
            }
            foreach ($data as $val){
                if($item['goodsId']==$val['goodsid']){
                    $item['status'] = $val['status'];
                    $item['skuName'] = $item['title'];
                    $item['title'] = $val["title"];
                    $item['spellPrice']=bcmul($item['price'],$val['discount']*0.01,2);
                    $result[]=array_merge($val,$item);
                }
            }

        }
        $this->success('ok',$result);

    }

    /**
     * @Explain :删除
     * @Date : 2020/9/7 16:59
     * @Author : 河南邦耀网络科技有限公司
     */
    public function remove(){
        $goods = $this->request->request("goods",'','urldecode');
        $goods=json_decode($goods,true);
        if(empty($goods)) $this->success('没有要删除的商品');
        foreach ($goods as $row) {
            $result = (new Cm())->where(['uid' => $this->auth->id,'goodsId'=>$row['goodsId'], 'skuId' => $row['skuId']])->delete();
        }
        if($result){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 结算数据
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="goodsId", type="string", required=true, description="商品ID为空代表购物车")
     * @ApiParams(name="skuId", type="string", required=true, description="规格ID")
     * @ApiParams(name="goodsNum", type="string", required=true, description="商品数量")
     * @ApiParams(name="model", type="string", required=true, description="类型1普通2拼价3拼团")
     */
    public function checkout()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $goods = $this->request->request("goods",0,'urldecode');
        $goods=json_decode($goods,true);
        if(empty($goods)) $this->error('商品信息参数错误');
        $model = $this->request->request("model",1);
        $countPrice = $tmp = 0;
        $goodsList = [];
        foreach ($goods as $row) {
            if (!empty($row['goodsId'])) {
                if (empty($row['quantity']) || intval($row['quantity']) <= 0) {
                    $this->error("商品数量不能为空");
                }
                $goodsInfo = \app\admin\model\goods\Goods::where('goodsid', $row['goodsId'])->where('status', 1)->field('title,image,price,discount')->find();
                $goodsInfo["goodsNum"] = $row['quantity'];
                $skuInfo = [];
                if (!empty($row['skuId'])) {
                    $skuInfo = \app\admin\model\goods\GoodsSkuDetail::where('goodsid', $row['goodsId'])->where('skuId', $row['skuId'])->field('title,image,price')->find();
                    $tmp = bcmul($skuInfo['price'], $row['quantity'], 2);
                    $countPrice += bcmul($skuInfo['price'], $row['quantity'], 2);
                    $skuInfo["skuNum"] = $row['quantity'];
                } else {
                    $countPrice += bcmul($goodsInfo['price'], $row['quantity'], 2);
                    $tmp = bcmul($goodsInfo['price'], $row['quantity'], 2);
                }
                if ($model == 2) {
                    $countPrice-=$tmp;
                    $countPrice += bcmul($tmp, $goodsInfo['discount'] * 0.01, 2);
                    $goodsInfo['price'] = bcmul($goodsInfo['price'], $goodsInfo['discount'] * 0.01 , 2);
                    if (!empty($skuInfo)) {
                        $skuInfo["price"] = bcmul($skuInfo['price'], $goodsInfo['discount'] * 0.01 , 2);
                    }
//                    $goodsInfo['price'] = $goodsInfo['price'];
//                    if (!empty($skuInfo)) {
//                        $skuInfo["price"] = $skuInfo['price'];
//                    }
                }
                $goodsInfo['skuInfo'] = $skuInfo;
                $goodsList[] = $goodsInfo;
            } else {
                continue;
            }
        }
        $addressInfo = Db::table('pt_address')->where(['uid'=>$this->auth->id])->where('isdefault',1)->field('id,username,mobile,province,city,district,address')->find();
        $data = array(
            "goods"=>$goodsList,
            "countPrice"=>bcmul($countPrice,1,2),
            "address"=>!empty($addressInfo)?[$addressInfo]:[],
            "payTypeInfo"=>array_values($this->getPayType()),
            "model"=>$model,
            "percent"=>70,
        );
        $this->success("结算信息",$data);
    }

    /**
     * 获取支付方式
     * @ApiInternal
     */
    public function getPayType()
    {
        return [
            "wechat"=>array(
                "title"=>"微信支付",
                "payType"=>"wechat",
                "status"=>\think\config::get("site.wechatpaystatus"),
                "tips"=>"(推荐)",
            ),
            "alipay"=>array(
                "title"=>"支付宝支付",
                "payType"=>"alipay",
                "status"=>\think\config::get("site.alipaypaystatus"),
                "tips"=>"(可安全免密支付)",
            ),
            "credit"=>array(
                "title"=>"余额支付",
                "payType"=>"credit",
                "status"=>1,
                "price"=>$this->auth->money,
                "tips"=>"(￥".$this->auth->money.")",
            ),
        ];
    }

    private function assoc_unique($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }

        return $tmp_arr;
    }

}
